package com.atguigu.oss.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.utils.R;
import com.atguigu.oss.utils.OssConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传
 */
@Slf4j
@RestController
@RequestMapping("/eduoss/fileoss")
@Api(description = "文件上传 头像/图片上传-8002")
public class OssController {

    @ApiOperation(value = "文件上传")
    @PostMapping
    public R fileUpLoad(MultipartFile file) {
        if (null == file) {
            return R.error().message("内容不可为空");
        }
        String endPoint = OssConfig.END_POINT;
        String accesskeyid = OssConfig.ACCESSKEYID;
        String accesskeysecret = OssConfig.ACCESSKEYSECRET;
        String bucketname = OssConfig.BUCKETNAME;
        String filename = file.getOriginalFilename();
        String dateStr = new DateTime().toString("yyyy/MM/dd");
        String uuidStr = UUID.randomUUID().toString().replaceAll("-", "");
        //  拼接文件名称及文件夹2012/02/03a.jpg
        filename = dateStr + "/" + uuidStr + filename;
        OSS oss = new OSSClientBuilder().build(endPoint, accesskeyid, accesskeysecret);
        try {
            //执行上传操作
            //此处可能有中文乱码问题 导致请求不到
            oss.putObject(bucketname, filename, file.getInputStream());
            return R.ok().data("url", "https://" + bucketname + "." + endPoint + "/" + filename);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error().message(e.getMessage());
        } finally {
            oss.shutdown();
        }

    }
}
